<template>
	<div class="content_page" v-if="status">
    <!--  上方搜索框  -->
    <searchBar
      @addStock = 'addStock'
      ref="searchBarRef"
      :class="{'showBar': showSearchInput}"
    >
    </searchBar>

    <!--  股票列表  -->
    <div class="stock-list" :class="{'hideStockList': stockListHide}">
      <div class="stock-title">
        <img src="../../assets/images/add.png"  @click="showAddInput" alt="" class="add-icon" title="添加股票">
        <img src="../../assets/images/refresh.png"  @click="refreshData" alt="" class="add-icon" title="刷新">
        <img src="../../assets/images/sort.png"  @click="sortData" alt="" class="add-icon" title="排序">
        <img src="../../assets/images/save.png"  @click="save" alt="" class="add-icon" title="将自选股票及预警信息缓存到当前网站，当您需要重新安装本插件时可以进行此操作，重装完成后，请重新进入当前网站，点击旁边的导入按钮，即可恢复数据">
        <img src="../../assets/images/import.png"  @click="importData" alt="" class="add-icon" title="将缓存在当前站点的数据重新载入">
        <img src="../../assets/images/clear.png"  @click="clearData" alt="" class="add-icon" title="清理全部数据">
      </div>
      <div class="stockList-ctn">
        <div class="stockList">
          <div
            v-for="(item, index) in stockList"
            :key="item.code"
            class="stockItem"
            :class="{'stockGreen':item.increase < 0 }"
            :title="`${item.name} ${item.code}&#10;今开${item.open} 昨收${item.yestclose}&#10;最高${item.high} 最低${item.low}&#10;成交量${item.volume} 成交额${item.amount}`"
            @contextmenu="showContextmenu(item, index, $event)">
            <div class="stockItem-main">
              <span class="increase-icon" v-show="item.increase < 0">↓</span>
              <span class="increase-icon" v-show="item.increase >= 0">↑</span>
              <span class="increase">{{item.increase}}%</span>
              <span class="price">{{item.price}}</span>
              <div style="display: flex;align-items: center">
                <span class="name">{{item.name}}</span>
                <span class="us-icon" v-if="item.code.startsWith('us')">us</span>
                <span class="hk-icon" v-if="item.code.startsWith('hk')">hk</span>
              </div>
              <img
               src="../../assets/images/warning.png"
               class="warning-icon"
               :title="`${item.warnTitle}`"
               v-show="item.isWarn">
            </div>
            <div class="ops-ctn">
              <img src="../../assets/images/del.png" class="del-icon" alt="删除" title="删除" @click="delStock(item)">
            </div>
          </div>
          <!-- 添加预警弹窗 -->
          <div class="warn-ctn" v-show="warnShow">
            <div class="warn-main">
              <div>
                {{warnName}}【{{warnCode}}】
              </div>
              <div>当前价格：{{warnStockNowPrice}}</div>
              <input type="number" v-model="warnPrice" min="0" placeholder="请输入预警价格" class="warn-input">
              <div class="warn-btn-ctn">
                <button style="margin-right:10px" @click="addWarn">确定</button>
                <button @click="cancelWarn">取消</button>
              </div>
            </div>
          </div>
        </div>
        <!--    右键菜单    -->
        <div id="stockRightMenu">
          <div class="menu" @click="changePosition('top')">置顶</div>
          <div class="menu" @click="changePosition('bottom')">置底</div>
          <div class="menu" @click="stockWarn">股价预警</div>
        </div>
      </div>
      <img src="../../assets/images/open.png" class="open-icon" @click="hideList">
    </div>
	</div>
</template>

<script>
import { reactive, toRefs, toRaw, onMounted, ref } from 'vue';
import {
  getChromeLocalStorage,
  setChromeLocalStorage,
  getLocalStorage,
  setLocalStorage,
  sortStock,
  sendMessageToBackgroundPopupScript
} from '../../assets/js/utils'
import searchBar from './searchBar';
  export default {
    components: {
      searchBar
    },
    setup() {
      const searchBarRef = ref(null)
      const data = reactive({
        needRefreshData: true,
        rightClickItem: {},
        rightClickIndex: -1,
        // 搜索框
        status: false,
        searchKey: '',
        suggestList: '',
        showSearchInput: false,
        showSearchList: false,
        // 股票列表
        sortType: 0,
        stockListHide: true,
        stockList: [],
        stockCodeList: ['sh000001', 'sz399001', 'sz399006'],
        // 股价预警
        warnList: {},
        warnShow: false,
        warnCode: '',
        warnPrice: '',
        warnName: '',
        warnStockNowPrice: ''
      })
      onMounted(async () => {
        getBgMessage();
        getChromeLocalStorage('stockCodeList', (stockCodeList) => {
          if (stockCodeList && stockCodeList[0]) {
            data.stockCodeList = Array.from(new Set(stockCodeList))
          }
        })
        getChromeLocalStorage('stockWarnList', (warnList) => {
          data.warnList = warnList || {}
        })
        monitorKey(data, searchBarRef)
        setInterval(() => {
          refreshData()
        }, 5000)
        pageVisibilitychange()
      });
      const changePosition = (type) => {
        const index = data.rightClickIndex
        const target = {...data.stockList[index]}
        const targetCode = data.stockCodeList[index]
        data.stockList.splice(index, 1)
        data.stockCodeList.splice(index, 1)
        if (type === 'top') {
          data.stockList.unshift(target)
          data.stockCodeList.unshift(targetCode)
        } else {
          data.stockList.push(target)
          data.stockCodeList.push(targetCode)
        }
        setChromeLocalStorage('stockCodeList', toRaw(data.stockCodeList))
      }
      // 右键菜单
      const showContextmenu = (item, index, e) => {
        console.log(index)
        e.preventDefault();
        data.rightClickItem = item
        data.rightClickIndex = index
        const menu = document.querySelector('#stockRightMenu');
        menu.style.left = e.clientX + 'px';
        menu.style.top = e.clientY + 'px';
        menu.style.width = '90px';
      }
      // 页面激活判断
      const pageVisibilitychange = () => {
        document.addEventListener('visibilitychange', (event) => {
          if (document.webkitHidden) {
            data.needRefreshData = false
          } else {
            let haveWarnItem = false
            for (const key in data.warnList) {
              if (data.warnList[key]) {
                haveWarnItem = true
              }
            }
            if (haveWarnItem) {
              data.needRefreshData = true
            } else {
              if (data.stockListHide) {
                data.needRefreshData = false
              } else {
                data.needRefreshData = true
              }
            }
          }
        })
      }
      // 发送桌面通知
      const showNotification = (title, data) => {
        sendMessageToBackgroundPopupScript({
          greeting: 'showNotification',
          data: { title, data }
        }, res => {

        })
      }
      // 股票预警
      const stockWarn = () => {
        const item = data.rightClickItem
        data.warnCode = item.code
        data.warnName = item.name
        data.warnStockNowPrice = item.price
        data.warnShow = true
      }
      // 添加预警
      const addWarn = () => {
        if (!data.warnPrice) {
          return
        }
        const flag = data.warnPrice - data.warnStockNowPrice > 0 ? 'rise' : 'fall'
        const _data = data.warnList[data.warnCode]
        let isRepeat = false
        if (_data) {
          _data.forEach((item) => {
            if (item.targetPrice === data.warnPrice) {
              isRepeat = true
            }
          })
          if (isRepeat) {
            return
          } else {
            data.warnList[data.warnCode].push({
              type: flag,
              targetPrice: data.warnPrice
            })
          }
        } else {
          data.warnList[data.warnCode] = [{
              type: flag,
              targetPrice: data.warnPrice
            }]
        }
        setChromeLocalStorage('stockWarnList', toRaw(data.warnList))
        data.warnShow = false
        data.warnCode = ''
        data.warnName = ''
      }
      const cancelWarn = () => {
        data.warnShow = false
        data.warnCode = ''
        data.warnName = ''
      }
      // 显示搜索框
      const showAddInput = () => {
        data.showSearchInput = true
      }
      // 排序
      const sortData = () => {
        const _sortType = data.sortType + 1 === 2 ? -1 : data.sortType + 1
        data.sortType = _sortType
        data.stockList = sortStock(data.stockList, _sortType)
        if (_sortType === 0) {
          refreshData()
        }
      }
      // 刷新数据
      const refreshData = () => {
        let haveWarnItem = false
        for (const key in data.warnList) {
          if (data.warnList[key]) {
            haveWarnItem = true
          }
        }
        if (haveWarnItem) {
          data.needRefreshData = true
        } else {
          if (data.stockListHide) {
            data.needRefreshData = false
          } else {
            data.needRefreshData = true
          }
        }
        if (data.stockCodeList[0] && data.status && data.needRefreshData) {
          requireData()
        }
      }
      const requireData = () => {
        console.log('request')
        sendMessageToBackgroundPopupScript({
          greeting: 'getStockList',
          data: { codeList: data.stockCodeList }
        }, res => {
          res.forEach((item) => {
            // 计算涨幅
            item.increase = ((item.price - item.yestclose) / item.yestclose * 100).toFixed(2)
            // 如果当前有打开添加预警的弹窗，预警股票的价格要实时更新
            if (data.warnCode && item.code === data.warnCode) {
              data.warnStockNowPrice = item.price
            }
            if (data.warnList[item.code]) {
              item.isWarn = true
              item.warnTitle = ''
              data.warnList[item.code].forEach((warnItem, index) => {
                // 添加到了预警提示
                item.warnTitle += warnItem.type === 'rise' ? '涨' : '跌'
                item.warnTitle += `到${warnItem.targetPrice}时预警`
                if (index < data.warnList[item.code].length - 1) {
                  item.warnTitle += '||'
                }
                // 判断是否达到预计阙值
                if (warnItem.type === 'rise' && item.price >= warnItem.targetPrice) {
                  showNotification('股票助手', `${item.name}【${item.code}】已涨到您设置的预警价位${warnItem.targetPrice}`);
                  data.warnList[item.code].splice(index, 1)
                  setChromeLocalStorage('stockWarnList', toRaw(data.warnList))
                } else if (warnItem.type === 'fall' && item.price <= warnItem.targetPrice) {
                  showNotification('股票助手', `${item.name}【${item.code}】已跌到您设置的预警价位${warnItem.targetPrice}`);
                  data.warnList[item.code].splice(index, 1)
                  setChromeLocalStorage('stockWarnList', toRaw(data.warnList))
                }
              })
            }
          })
          data.stockList = sortStock(res, data.sortType)
        })
      }
      // 添加股票
      const addStock = (code) => {
        if (!data.stockCodeList.includes(code)) {
          data.stockCodeList.unshift(code)
          getStockList(data.stockCodeList)
        }
      }
      // 删除股票
      const delStock = (stock) => {
        data.stockCodeList.forEach((item, index) => {
          if (item === stock.code) {
            data.stockCodeList.splice(index, 1)
          }
        })
        setChromeLocalStorage('stockCodeList', toRaw(data.stockCodeList))
        data.stockList.forEach((item, index) => {
          if (item.code === stock.code) {
            data.stockList.splice(index, 1)
          }
        })
      }
      // 隐藏股票列表
      const hideList = () => {
        data.stockListHide = !data.stockListHide
      }
      const getStockList = (codeList) => {
        sendMessageToBackgroundPopupScript({
          greeting: 'getStockList',
          data: { codeList }
        }, res => {
          const codeList = res.map((item) => {
            return item.code
          })
          const _codeList = []
          res.forEach((item) => {
            _codeList.push(item.code)
            item.increase = ((item.price - item.yestclose) / item.yestclose * 100).toFixed(2)
          })
          data.stockList = sortStock(res, data.sortType)
          data.stockCodeList = _codeList
          setChromeLocalStorage('stockCodeList', _codeList)
        })
      }
      // 页面加载时获取当前的插件状态
      const getBgMessage = () => {
        sendMessageToBackgroundPopupScript({
          greeting: 'getBackGroundMessage'
        }, info => {
          if (!info.popopActive) {
            data.status = false;
          } else {
            data.status = true;
          }
        })
      };
      // 插件激活状态改变时触发
      chrome.runtime.onMessage.addListener((request, sendResponse) => {
        if (request.type === 'activeChange') {
          data.status = request.active
          return true
        }
        sendResponse();
      });
      // 将数据缓存到当前站点
      const save = () => {
        if (data.stockCodeList[0]) {
          setLocalStorage('stockCodeList', data.stockCodeList)
          setLocalStorage('stockWarnList', data.warnList)
          alert('自选股票及预警信息已缓存到当前网站，请您重新安装安装完成插件后回到当前网站点击导入按钮')
        }
      }
      // 导入
      const importData = () => {
        const stockCodeList = getLocalStorage('stockCodeList') || '[]'
        const stockWarnList = getLocalStorage('stockWarnList') || '{}'
        if (data.stockCodeList && data.stockCodeList[0]) {
          const r = confirm('当前列表已有自选股票，继续导入将会覆盖当前列表，是否继续导入？');
          if (r === true) {
              data.stockCodeList = stockCodeList
              data.warnList = stockWarnList
              setChromeLocalStorage('stockWarnList', stockWarnList)
              setChromeLocalStorage('stockCodeList', stockCodeList)
              alert('导入成功')
          } else {

          }
        } else {
          data.stockCodeList = stockCodeList
          data.warnList = stockWarnList
          setChromeLocalStorage('stockWarnList', stockWarnList)
          setChromeLocalStorage('stockCodeList', stockCodeList)
          alert('导入成功')
        }
      }
      const clearData = () => {
        data.stockCodeList = []
        data.stockList = []
        data.warnList = {}
        setChromeLocalStorage('stockCodeList', toRaw(data.stockCodeList))
        setChromeLocalStorage('stockWarnList', toRaw(data.warnList))
      }
      return {
        ...toRefs(data),
        getBgMessage,
        hideList,
        addStock,
        delStock,
        showAddInput,
        refreshData,
        sortData,
        stockWarn,
        cancelWarn,
        addWarn,
        save,
        importData,
        showContextmenu,
        changePosition,
        clearData,
        searchBarRef
      };
    }
	}
	// 监听按键
  function monitorKey (state, searchBarRef) {
    document.onkeyup = (e) => {
      if (e && e.shiftKey && e.keyCode === 70) { // 按  shift + f 显示搜索框
        state.showSearchInput = true
      }
      if (e && e.keyCode === 27) { // 按 Esc 隐藏搜搜框
        if (!state.showSearchInput) {
          state.stockListHide = true
        }
        state.showSearchInput = false
        searchBarRef.value.hide()
      }
    }
    window.onclick = () => {
      const menu = document.querySelector('#stockRightMenu');
      menu.style.width = '0px';
    }
  }
</script>

<style lang="less" scoped>
  * {
    box-sizing: border-box;
  }
  #stockRightMenu{
    background: #ffffff;
    width: 0;
    overflow: hidden;
    box-shadow: 0 1px 1px #888,1px 0 1px #ccc;
    position: fixed;
    z-index: 999999;
  }
  .menu{
    cursor: pointer;
    text-align: left;
    width: 90px;
    height: 25px;
    line-height: 25px;
    padding: 0 10px;
    &:hover {
      background: #eeeeee;
    }
  }
  .us-icon {
    color: #ffffff;
    display: inline-block;
    height: 14px;
    line-height: 14px;
    font-size: 12px;
    transform: scale(0.8);
    background: rgba(149, 69, 96);
  }
  .name {
    display: inline-block;
    width: 70px;
    text-overflow:ellipsis;
    overflow: hidden;
    white-space:nowrap;
  }
  .hk-icon {
    color: #ffffff;
    display: inline-block;
    height: 14px;
    line-height: 14px;
    font-size: 12px;
    transform: scale(0.8);
    background: rgba(55, 88, 150);
  }
  .warning-icon {
    margin-left: 5px;
    width: 12px;
    height: 12px;
  }
  .warn-input {
    margin: 5px 0 10px;
    border: 1px solid rgb(204,204,204);
  }
  .warn-btn-ctn {
    text-align: center;
  }
  .warn-ctn {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
    background: rgba(255, 255, 255, 0.8);
    .warn-main {
      background: #ffffff;
      border: 1px solid rgb(204,204,204);
      padding:5px 10px;
      width: 200px;
      position: absolute;
      top: 30%;
      left: 50%;
      transform: translate(-50%,0);
    }
  }
  .add-icon {
    cursor: pointer;
    width: 16px;
    height: 16px;
  }
  .stock-title {
    height: 32px;
    display: flex;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid rgb(204,204,204);
    img {
      margin-right: 10px;
    }
  }
  .stockItem-main {
    position: relative;
    display: flex;
    align-items: center;
    .increase-icon {
      margin-right: 5px;
    }
  }
  .stockList-ctn {
    position: relative;
    height: 468px;
    overflow-y: auto;
  }
  .stockList {
    height: 100%;
    overflow-y: auto;
  }
  .ops-ctn {
   display: none;
   align-items: center;
   img {
     margin-left: 10px;
   }
  }
  .del-icon {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .increase {
    text-align: right;
    display: inline-block;
    width: 56px;
    margin-right: 8px;
  }
  .price {
    display: inline-block;
    width: 80px;
    text-align: right;
    padding-right: 10px;
  }
  .open-icon {
    cursor: pointer;
    width: 30px;
    height: 30px;
    position: absolute;
    left: -30px;
    top: 50%;
    transform: translate(0, 50%);
    z-index: 99999;
  }
	.stock-list{
    font-size: 14px;
    border-radius: 3px;
    border:1px solid rgb(204,204,204);
		background: #ffffff;
		position: fixed;
    width: 300px;
    height: 500px;
		z-index: 100001;
		right: 0;
		bottom: 0;
    transition: all 1s inherit;
	}
  .hideStockList {
    right: -300px
  }
  .showBar {
    top: 20px!important;
  }
  .stockItem {
    color: red;
    line-height: 26px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    >span {
      display: inline-block;
      margin-right: 10px;
    }
    &:hover {
      background: rgb(245,247,250);
      .ops-ctn {
        display: flex;
      }
    }

  }
  .stockGreen {
    color: green;
  }
  * {
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background-color: rgba(144, 147, 153, 0.3);
    }

    &::-webkit-scrollbar-track {
      //background-color: ;
    }
  }
</style>
